package com.joker.other;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

public class MyRealm extends AuthorizingRealm {

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权道路开始了");
        String pr=(String)principalCollection.getPrimaryPrincipal();
        System.out.println("身份信息为 "+pr);
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("admin");
        simpleAuthorizationInfo.addRole("user");
        // 这个用户对于 001 这个资源有着所有的操作权限
        simpleAuthorizationInfo.addStringPermission("user:*:001");
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 取到用户名
        String name=(String)authenticationToken.getPrincipal();
        System.out.println("自定义Realm "+name+" ");
        // 判断用户是否存在，连接数据库
        if(name.equals("joker")){

            // 这里的 “f3aed468e9246cbdff61fc59084154e0” Md5Test 算出来的 ，是数据库中查到的密码
            // ByteSource.Util.bytes("xod") 这个是随机盐salt
            SimpleAuthenticationInfo simpleAccountRealm=new SimpleAuthenticationInfo(name,"f3aed468e9246cbdff61fc59084154e0", ByteSource.Util.bytes("xod"),this.getName());
            return simpleAccountRealm;
        }
        return null;
    }
}
